<template>
  <view class="honor-info-form">
    <!-- 使用通用展示组件 -->
    <DetailDisplayList
      :config="config"
      :list="honorList"
      :loading="loading"
      @add="handleAddHonor"
      @edit="handleEditHonor"
      @delete="handleDeleteHonor"
    >
      <!-- 自定义文件展示 -->
      <template #file-display="{ item }">
        <view v-if="item.TitleDocument" class="file-attachment">
          <button class="file-button" @click="previewFile(item.TitleDocument)">
            <i
              class="iconfont icon-wenjian"
              style="font-size: 14px; color: #3b82f6; margin-right: 4px"
            ></i>
            {{ item.TitleDocument.FileName || "查看证书" }}
          </button>
        </view>
      </template>
    </DetailDisplayList>

    <!-- 弹窗已移动到父页面顶层 -->
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import SysHrInterviewRequestBillApi from "../api/index";
import type {
  IHonorResponse,
  IHonorRequest,
  ISubTableSearchRequest,
} from "../api/interface";
import DetailDisplayList from "./DetailDisplayList.vue";
import { honorDisplayConfig } from "./detailDisplayConfig";
import { honorConfig } from "./popupConfigs";

const api = SysHrInterviewRequestBillApi();

// Props
interface Props {
  personId: string;
}

const props = defineProps<Props>();

// 状态管理
const loading = ref(false);
const honorList = ref<IHonorResponse[]>([]);
const editingHonor = ref<IHonorResponse | null>(null);

// Emits
const emit = defineEmits<{
  add: [];
  edit: [item: IHonorResponse];
}>();

// 详情展示配置
const config = ref(honorDisplayConfig);

// 弹框配置（用于加载资质类别选项）
const honorPopupConfig = ref(JSON.parse(JSON.stringify(honorConfig)));

// 移除了荣誉职称提交处理，因为弹框已移到父组件

// 加载荣誉职称列表
const loadHonorList = async () => {
  if (!props.personId) return;

  loading.value = true;
  try {
    const params: ISubTableSearchRequest = {
      Limit: 50,
      Page: 1,
      PersonId: props.personId,
      SortInfo: null,
    };

    const res = await api.getHonorList(params);
    if (res && res.Data) {
      honorList.value = res.Data;
    }
  } catch (error) {
    console.error("加载荣誉职称失败:", error);
    uni.showToast({
      title: "加载荣誉职称失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

// 加载资质类别数据
const loadProfessionalTitleTypes = async () => {
  try {
    const res = await api.getProfessionalTitleTypes();
    console.log("资质类别API返回数据:", res);

    if (res && Array.isArray(res)) {
      // 找到资质类别字段并更新选项
      const section = honorPopupConfig.value.sections.find(
        (s: any) => s.key === "honor_info",
      );
      if (section) {
        const row = section.rows.find((r: any) => r.key === "row1");
        if (row) {
          const field = row.fields.find(
            (f: any) => f.key === "ProfessionalTitleTypeId",
          );
          if (field) {
            const options = res.map((item) => {
              console.log("处理资质类别项:", item);
              return {
                value: item.Value,
                text: item.Text,
              };
            });
            console.log("转换后的选项数据:", options);
            field.options = options;
          }
        }
      }
    } else {
      console.log("资质类别数据为空或格式不正确:", res);
    }
  } catch (error) {
    console.error("加载资质类别失败:", error);
    uni.showToast({
      title: "加载资质类别失败",
      icon: "none",
    });
  }
};

// 新增荣誉职称
const handleAddHonor = () => {
  if (!props.personId) {
    uni.showToast({ title: "缺少人员信息", icon: "none" });
    return;
  }
  editingHonor.value = null;
  // 发出事件给父组件处理（父组件会加载资质类别数据）
  emit("add");
};

// 编辑荣誉职称
const handleEditHonor = (item: IHonorResponse) => {
  if (!props.personId) {
    uni.showToast({ title: "缺少人员信息", icon: "none" });
    return;
  }
  editingHonor.value = item;
  // 发出事件给父组件处理（父组件会加载资质类别数据）
  emit("edit", item);
};

// 删除荣誉职称
const handleDeleteHonor = (item: any) => {
  const id = item.ID;
  if (!id) return;

  uni.showModal({
    title: "确认删除",
    content: "确定要删除这条荣誉职称记录吗？",
    success: async (res) => {
      if (res.confirm) {
        try {
          await api.deleteHonor([id]);
          // 重新加载列表
          await loadHonorList();
          uni.showToast({
            title: "删除成功",
            icon: "success",
          });
        } catch (error) {
          console.error("删除荣誉职称失败:", error);
          uni.showToast({
            title: "删除失败",
            icon: "error",
          });
        }
      }
    },
  });
};

// 预览文件
const previewFile = async (file: any) => {
  if (!file?.ID) return;

  try {
    await api.previewFile(file.ID, file.FileName || undefined);
  } catch (error) {
    console.error("预览文件失败:", error);
    uni.showToast({
      title: "预览失败",
      icon: "none",
    });
  }
};

// 移除了确认新增方法，因为弹框已移到父组件

// 监听personId变化
watch(() => props.personId, loadHonorList, { immediate: true });

// 页面加载
onMounted(() => {
  if (props.personId) {
    loadHonorList();
  }
});

// 导出方法供父组件调用
defineExpose({
  loadHonorList,
});
</script>

<style lang="scss" scoped>
.honor-info-form {
  // 保留文件按钮样式，因为在自定义插槽中使用
  .file-attachment {
    .file-button {
      background: rgba(59, 130, 246, 0.1);
      color: #3b82f6;
      border: 1rpx solid #3b82f6;
      border-radius: 8rpx;
      padding: 8rpx 16rpx;
      font-size: 24rpx;
      display: flex;
      align-items: center;
      transition: all 0.3s ease;

      &:active {
        background: rgba(59, 130, 246, 0.2);
      }
    }
  }
}
</style>
